package com.luyuan.crm.member.web;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.faces.event.ActionEvent;
import javax.faces.model.DataModel;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.luyuan.crm.member.model.Member;
import com.luyuan.crm.member.model.MemberGroup;
import com.luyuan.crm.member.model.MemberIntegral;
import com.luyuan.crm.member.model.MemberLevel;
import com.luyuan.crm.member.service.MemberIntegralService;
import com.luyuan.crm.member.service.MemberService;
import com.luyuan.crm.sms.Constant;
import com.luyuan.crm.sms.service.SmsService;
import com.luyuan.crm.user.Party;
import com.ruijie.components.security.model.AppUser;
import com.ruijie.components.security.model.Role;
import com.ruijie.components.setting.service.SettingService;
import com.ruijie.foundation.query.Page;
import com.ruijie.foundation.query.criteria.CriteriaTemplate;
import com.ruijie.foundation.query.criteria.RestrictionTemplate;
import com.ruijie.foundation.security.AppUserContext;
import com.ruijie.util.StringUtils;
import com.ruijie.web.jsf.action.BaseAction;
import com.ruijie.web.jsf.context.TableContext;
import com.ruijie.web.jsf.model.PageDataModel;
import com.ruijie.web.jsf.model.TableOrder;
import com.ruijie.web.jsf.model.TablePage;

@Component("memberActionForManager")
@Scope("view")
public class MemberActionForManager extends BaseAction implements InitializingBean {

    private final static Log logger = LogFactory.getLog(MemberActionForManager.class);

    @Resource(name = "memberService")
    private MemberService memberService;

    @Resource(name = "memberIntegralService")
    private MemberIntegralService memberIntegralService;

    @Resource(name = "smsService")
    private SmsService smsService;

    private String smsContent;

    @Autowired
    private SettingService settingService;

    public String getSmsContent() {
        return smsContent;
    }

    public void setSmsContent(String smsContent) {
        this.smsContent = smsContent;
    }

    // 查询条件
    private Member criteria = new Member();

    private MemberLevel levelCriteria;

    private MemberGroup groupCriteria;

    // 添加或编辑模型
    private Member member = null;

    private MemberIntegral memberIntegral = null;

    private String assignMemberId;

    private Party support;

    private Date startDate;

    private Date endDate;

    public Party getSupport() {
        return support;
    }

    public void setSupport(Party support) {
        this.support = support;
    }

    public Member getMemberModel() {
        return member;
    }

    public MemberIntegral getMemberIntegral() {
        if (memberIntegral == null) {
            if (member == null) {
                member = memberService.getByAccount((AppUser) AppUserContext.getCurrentUser());
            }
            memberIntegral = memberIntegralService.getMemberIntegral(member);
        }
        if (memberIntegral == null) {
            memberIntegral = new MemberIntegral();
        }
        return memberIntegral;
    }

    public Member getCriteria() {
        return criteria;
    }

    public DataModel getTableModel() {
        TablePage tablePage = TableContext.getTablePage();
        if (tablePage == null) {
            return new PageDataModel(new Page());
        }

        List<TableOrder> tableOrders = TableContext.getTableOrders();
        List<Order> orders = new ArrayList<Order>();
        for (TableOrder tableOrder : tableOrders) {
            Order order = tableOrder.toOrder();
            if (order != null) {
                orders.add(order);
            }
        }

        CriteriaTemplate c = getCriterialTemplate();

        orders.add(Order.desc("activeTime"));
        Page page = memberService.pagedQuery(c, tablePage.getPage(), tablePage.getPageSize(), orders);
        return new PageDataModel(page);
    }

    public void exportCriteriaTemplate(ActionEvent event) {
        setRequestAttribute("member.criteriaTemplate", getCriterialTemplate(), true);
    }

    private CriteriaTemplate getCriterialTemplate() {
        CriteriaTemplate c = CriteriaTemplate.forClass(Member.class);
        RestrictionTemplate r = new RestrictionTemplate(true);
        c.add(r.like("name", criteria.getName()));
        c.add(r.like("mobile", criteria.getMobile()));
        c.add(r.eq("support", support));
        if (levelCriteria != null) {
            c.createCriteria("memberIntegral", "integral").add(Restrictions.eq("integral.memberLevel", levelCriteria));
        }
        if (groupCriteria != null) {
            c.createCriteria("memberGroups", "group").add(Restrictions.eq("group.id", groupCriteria.getId()));
        }
        if (criteria.getLoyalty() != null) {
            c.add(Restrictions.eq("loyalty", criteria.getLoyalty()));
        }
        if (criteria.getLiveness() != null) {
            c.add(Restrictions.eq("liveness", criteria.getLiveness()));
        }

        if (startDate != null && endDate == null) {
            c.add(r.gt("activeTime", startDate));
        }
        else if (startDate == null && endDate != null) {
            c.add(r.lt("activeTime", endDate));
        }
        else if (startDate != null && endDate != null) {
            c.add(r.between("activeTime", startDate, endDate));
        }
        return c;
    }

    public void updateUser() {
        memberService.updateMember(member);

        addGlobalI18nMessage("crud_update_success_msg");
    }

    public void removeByIds() {
        String[] selectedIds = getSelectedIds();
        if (logger.isDebugEnabled()) {
            logger.debug("delete: " + Arrays.asList(selectedIds));
        }
    }

    private String[] getSelectedIds() {
        String[] result = getRequestParameterValues("id");
        if (result == null)
            result = new String[0];
        return result;
    }

    public boolean isClientManager() {
        AppUser appUser = (AppUser) AppUserContext.getCurrentUser();

        Set<Role> roles = appUser.getRoles();
        for (Role role : roles) {
            if ("售后经理".equals(role.getRoleName())) {
                return true;
            }
        }
        return false;
    }

    public void assignToSaler() {
        if (StringUtils.isNullOrEmpty(assignMemberId)) {
            return;
        }

        String[] memberIds = assignMemberId.split(";");
        for (String id : memberIds) {
            Member member = memberService.getById(id);
            member.setSupport(support);
            memberService.updateMember(member);

            String[] objects = new String[4];
            // 会员名
            objects[0] = member.getName();
            // 售后人员
            objects[1] = member.getSupport().getUserName();
            // 工作座机
            objects[2] = member.getSupport().getTelephone();

            String content = settingService.getSetting(Constant.SMS_CONTENT_SALES).getValue();
            content = content.replaceAll("#\\{会员姓名\\}", objects[0]).replaceAll("#\\{售后人员\\}", objects[1])
                    .replaceAll("#\\{工作座机\\}", objects[2]);

            smsService.sendMessage(member.getMobile(), content);
        }

        addGlobalI18nMessage("crud_assign_success_msg");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        String memberId = getRequestParameter("memberId");
        if (!StringUtils.isNullOrEmpty(memberId)) {
            member = memberService.getById(memberId);
        }
        if (member == null) {
            member = memberService.getByAccount((AppUser) AppUserContext.getCurrentUser());
        }
        if (member == null) {
            member = new Member();
        }

        assignMemberId = getRequestParameter("assignMemberId");
    }

    public void setLevelCriteria(MemberLevel levelCriteria) {
        this.levelCriteria = levelCriteria;
    }

    public MemberLevel getLevelCriteria() {
        return levelCriteria;
    }

    public Date getStartDate() {
        return startDate;
    }

    public void setStartDate(Date startDate) {
        this.startDate = startDate;
    }

    public Date getEndDate() {
        return endDate;
    }

    public void setEndDate(Date endDate) {
        this.endDate = endDate;
    }

    public MemberGroup getGroupCriteria() {
        return groupCriteria;
    }

    public void setGroupCriteria(MemberGroup groupCriteria) {
        this.groupCriteria = groupCriteria;
    }
}
